Thread Synchronizing
Thread synchronization is a mechanism used to control access to shared resources when multiple threads are running simultaneously. It prevents problems such as race conditions and inconsistent data.
In short: synchronized ensures that only one thread at a time can execute a particular synchronized method/block for the same lock, helping prevent race conditions.
class Demo {
static synchronized void display() {
System.out.println("Hello");
}
}
Now, if two threads call increment(), only one thread at a time can execute the synchronized method for the same Counter object. If method is not synchronized the value of count may be anything other than excepted, because the threads interfere with each other.
The join() calls ensure that the main thread waits for both threads to finish before printing the result.
class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}
public class SynchroThreadDemo {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.count);
}
}